const gulp = require("gulp");
const jshint = require("gulp-jshint");
const uglify = require("gulp-uglify");
const concat = require("gulp-concat");
const less = require("gulp-less");
const prefix = require("gulp-autoprefixer");
const cleanCss = require("gulp-clean-css");
const del = require("del");
// const bSync = require("browser-sync");

gulp.task("test", () => {
  return gulp
    .src(["app/scripts/**/*.js", "!app/scripts/vendor/**/*.js"])
    .pipe(jshint())
    .pipe(jshint.reporter("default"))
    .pipe(jshint.reporter("fail"));
});

gulp.task("clean", () => {
  return del(["dist"]);
});

gulp.task(
  "scripts",
  gulp.series("test", function scriptsInternal() {
    //通过gulp.series,顺序先执行test
    return gulp
      .src(["app/scripts/**/*.js", "!app/scripts/vendor/**/*.js"])
      .pipe(concat("main.min.js"))
      .pipe(uglify())
      .pipe(gulp.dest("dist/scripts"));
  })
);

gulp.task("styles", () => {
  return gulp
    .src("app/styles/main.less")
    .pipe(less())
    .pipe(cleanCss())
    .pipe(prefix())
    .pipe(gulp.dest("dist/styles"));
});

gulp.task("server", (done) => {
  bSync({
    server: {
      baseDir: ["dist", "app"],
    },
  });
  done();
});

gulp.task(
  "default",
  gulp.series(
    "clean",
    gulp.parallel("styles", "scripts"),
    "server",
    function watcher(done) {
      //添加watcher监测
      gulp.watch(
        ["app/scripts/**/*.js", "!app/scripts/vendor/**/*.js"],
        gulp.parallel("scripts")
      );
      gulp.watch("app/styles/main.less", gulp.parallel("styles"));
      gulp.watch("dist/**/*", bSync.reload); //实现修改后浏览器自动刷新
      done();
    }
  )
);
